package com.alienos.collide.math;

/*   Copyright 2010 Jonathan Wagner
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
public class Mathf {

    /**
     * See references for details of Fast inverse square root
     * http://en.wikipedia.org/wiki/Fast_inverse_square_root
     * http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf
     * 
     * @param x
     * @return
     */
    public final static float inverseSquareRoot(float x) {
        final float xhalf = 0.5f * x;
        // Convert float to bit value
        int bitValue = Float.floatToRawIntBits(x);
        // square with voodoo magic number
        bitValue = 0x5f3759df - (bitValue >> 1);
        // convert back to float
        x = Float.intBitsToFloat(bitValue);
        x = x * (1.5f - xhalf * x * x);
        return x;
    }

    public static final float squareRoot(float x) {
        return x * inverseSquareRoot(x);
    }

    /**
     * Clamp imput between min and max
     * 
     * @param input
     * @param min
     * @param max
     * @return
     */
    public static float clamp(float input, float min, float max) {
        return (input < min) ? min : (input > max) ? max : input;
    }

    /**
     * convienience, clamp between 0 and 1
     * 
     * @param input
     * @return
     */
    public static float saturate(float input) {
        return clamp(input, 0f, 1f);
    }
}
